package com.dly.blog.provider;


import com.dly.blog.security.UserAuth;
import com.dly.blog.service.DefaultDetailsService;
import com.dly.blog.token.AccountToken;
import com.dly.blog.token.AdminToken;
import com.dly.blog.token.EmailToken;
import com.dly.blog.token.WxLoginToken;
import jakarta.annotation.Resource;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.authority.mapping.GrantedAuthoritiesMapper;
import org.springframework.security.core.authority.mapping.NullAuthoritiesMapper;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.crypto.password.PasswordEncoder;

@EqualsAndHashCode(callSuper = true)
@Data
@Slf4j
@Configuration
public class AdminAuthenticationProvider extends BaseAuthenticationProvider implements AuthenticationProvider {

    @Resource
    private DefaultDetailsService defaultDetailsService;

    private final GrantedAuthoritiesMapper authoritiesMapper = new NullAuthoritiesMapper();


    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        AdminToken adminToken = (AdminToken) authentication;
        UserDetails userDetails = defaultDetailsService.loadUserByAccount((String) adminToken.getPrincipal());
        additionalAuthenticationChecks(userDetails, adminToken);
        EmailToken authenticated =  EmailToken.authenticated(userDetails, authentication.getCredentials(), authoritiesMapper.mapAuthorities(userDetails.getAuthorities()));
        authenticated.setDetails(authentication.getDetails());
        return authenticated;
    }

    @Override
    public boolean supports(Class<?> authentication) {
        return AdminToken.class.isAssignableFrom(authentication);
    }
}
